import React, { PureComponent } from 'react';
import cns from 'classnames';

import S from './index.m.less';

import showHide from '@wpt/showHide';

function frequency(fn, fps = 60) {
    let time = 0;
    let now = time;
    let ST;
    const newFn = (...args) => {
        clearTimeout(ST);
        now = Date.now();
        const distance = now - time;

        if (distance >= fps) {
            time = now;
            fn(...args);
        } else {
            ST = setTimeout(() => {
                newFn(...args);
            }, distance);
        }
    };
    return newFn;
}

@showHide
class NavBack extends PureComponent {
    static defaultProps = {
        top: 50,
        zIndex: 100,
        noAnimation: false,
        atTop: true,
    };

    state = {
        atTop: this.props.atTop,
    };

    componentDidMount() {
        this.onPageShow();
    }

    componentWillUnmount() {
        this.onPageHide();
    }

    onPageShow() {
        this.addEvents();
    }

    onPageHide() {
        this.removeEvents();
    }

    addEvents() {
        if (this.isListen || this.props.noAnimation) return;
        this.isListen = true;
        window.addEventListener('scroll', this.handler);
    }

    removeEvents() {
        this.isListen = false;
        window.removeEventListener('scroll', this.handler);
    }

    handler = frequency(() => {
        const scrollTop = $(window).scrollTop();
        this.setState({
            atTop: scrollTop < this.props.top,
        });
    }, 16);

    handleBack = () => {
        if (!(WPT.referrer || document.referrer)) {
            WPT.showPage('/home');
            return;
        }

        window.history.back();
    };

    render() {
        const { atTop } = this.state;

        return (
            <div className={S.root} style={{ zIndex: this.props.zIndex }}>
                <div className={cns(S.singleBack, atTop && S.show)} onClick={this.handleBack}>
                    <i className="wptFM icon-fm-arrowright-bolder" />
                </div>
                <div className={cns(S.container, !atTop && S.show)}>
                    <div className={S.back} onClick={this.handleBack}>
                        <i className="wptFM icon-fm-arrowright-bolder" />
                    </div>
                    <div className={S.content}>{this.props.children}</div>
                </div>
            </div>
        );
    }
}

export default class NavBackWarp extends PureComponent {
    render() {
        if (
            !WPT.os.wechat // 只有微信才使用
        ) {
            return null;
        }
        return <NavBack {...this.props} />;
    }
}
